import redis
import time

from utils import utils


def user_thread(*arg):
    db = redis.Redis(host="localhost", port=6379, decode_responses=True)

    user_id, order_id = arg
    where = db.hget(user_id, "where")
    while where != "exit":
        mode = db.hget(user_id, "mode")
        if where == "wait":
            wait_queue = utils.get_wait_queue(mode)
            if wait_queue[0] == user_id:
                station = utils.get_available_station(mode)
                if station:
                    time_stamp = utils.pop_wait_queue(mode, user_id)
                    utils.push_charge_queue(station, user_id, time_stamp)
                    db.hset(order_id, "station_id", station)
        elif where == "charge":
            order_id = db.hget(user_id, "order")
            station = db.hget(order_id, "station_id")
            current_len = int(db.zcard(station + "_QUEUE"))
            charge_len = int(db.get("CHARGE_LEN"))
            stations = utils.get_available_station(mode)
            if current_len < charge_len and station not in stations:
                db.zadd(mode + "_STATION", {station: utils.get_system_time()})
            is_serve = db.hget(station, "is_serve")
            if is_serve == "1":
                serve_id = db.hget(station, "serve_id")
                if serve_id == user_id and not db.exists(station + ":" + user_id):
                    utils.end_order(user_id)
            elif is_serve == "0" and user_id == utils.get_charge_queue(station)[0]:
                utils.start_order(user_id)
        time.sleep(0.1)
        where = db.hget(user_id, "where")
